﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using yiCommerce.Core;
using yiCommerce.Service.Authentication;
using yiCommerce.Service.Customers;
using yiCommerce.Service.Messages;

namespace yiCommerce.Controllers.api
{
    public class RegisterApiController : ApiController
    {
        private ICustomerRegistrationService _customerRegistrationService;

        private IWorkContext _workContext;
        private IMessageService _messageService;
        private IAuthenticationService _authenticationService;
        private ICustomerService _customerService;

        public RegisterApiController(ICustomerRegistrationService customerRegistrationService, IWorkContext workContext, IMessageService messageService, IAuthenticationService authenticationService, ICustomerService customerService)
        {
            _customerRegistrationService = customerRegistrationService;
            _workContext = workContext;
            _messageService = messageService;
            _authenticationService = authenticationService;
            _customerService = customerService;
        }

        public RegisterResult Regist(RegisterRequest request)
        {
            var result = new RegisterResult();
            var regResult = _customerRegistrationService.RegisterCustomer(new CustomerRegistrationRequest()
                {
                    CustomerId = _workContext.CurrentCustomer.Id,
                    Email = request.Email,
                    Password = request.Password,
                    UserName = request.UserName
                });

            if (regResult.Success)
            {
                result.Status = ConstInfo.ResultSuccessStatus;
                result.Message = _messageService.GetResourceValue(Messages.CustomerRegistrationService_RegisterSuccess, 0);
                result.RedirectUrl = Url.Route("statushomepage", new {customerid = _workContext.CurrentCustomer.Id});


                var customer = _customerService.GetCustomerById(_workContext.CurrentCustomer.Id);
                _authenticationService.SignIn(customer,true);
               
            }
            else
            {
                result.Status = ConstInfo.ResultFailedStatus;
                result.Message = regResult.Errors[0];
            }
            return result;
        }
    }


    public class RegisterRequest
    {
        public string Email { get; set; }
        public string Password { get; set; }
        public string UserName { get; set; }
    }

    public class RegisterResult
    {
        public string Status { get; set; }
        public string Message { get; set; }

        public string RedirectUrl { get; set; }
    }
}
